package cn.kgc.springboot.day05.redis;

import jakarta.annotation.Resource;
import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

/**
 * @author 课工场
 * @date 2024/3/22
 * @description  redis缓存类
 */
public class RedisCache implements Cache {


    //缓存数据命名空间的名字
    private String id;

    public RedisCache(String id){
        this.id = id;
    }


    @Override
    public String getId() {
        return this.id;
    }

    //  缓存数据到二级缓存
    @Override
    public void putObject(Object key, Object value) {
        RedisTemplate redisTemplate = getRedisTemplate();
        redisTemplate.opsForHash().put(id,key.toString(),value);
    }

    // 从二级缓存中获取数据
    @Override
    public Object getObject(Object key) {
        return getRedisTemplate().opsForHash().get(id, key.toString());
    }

    @Override
    public Object removeObject(Object key) {
        return null;
    }


    // 清空缓存
    @Override
    public void clear() {
        getRedisTemplate().delete(id);
    }

    @Override
    public int getSize() {

        return getRedisTemplate().opsForHash().size(id).intValue();
    }


    public RedisTemplate  getRedisTemplate(){
        RedisTemplate bean = (RedisTemplate) ApplicationContextUtil.getBean("redisTemplate");
        // 设置redis中key的序列化方案   String
        bean.setKeySerializer(new StringRedisSerializer());
        bean.setHashKeySerializer(new StringRedisSerializer());
        return  bean;
    }
}
